import {defineStore} from 'pinia'
import {useAccountStore} from "./AccountStore.ts";
import {CacheMap, useCache} from "../utils/CacheUtils.ts";
import type {FavorFolder} from "../network/types/Favor.ts";

const api = () => useAccountStore().getNgaApi().favor;

export const useFavorStore = defineStore('FavorStore', {
    state: () => ({
        cacheFolder: new CacheMap<FavorFolder[]>(),
        favorFolders: [] as FavorFolder[],
    }),
    actions: {
        async folderList(userId: number, page?: number | undefined, force?: boolean | undefined) {
            const key = `${userId}`
            return useCache(this.cacheFolder, key, force || false, () => api().folderList(userId, page), 5 * 60).then(res => {
                this.favorFolders = res;
                return res
            })
        },
        folderModify(folderId: number, name: string, isPublic: boolean) {
            return api().folderModify(folderId, name, isPublic)
        },
        topicDelete(folderId: number, favorId: string[]) {
            return api().topicDelete(folderId, favorId)
        },
        topicAdd(folderId: number, tid: number, pid?: number | undefined) {
            return api().topicAdd(folderId, tid, pid)
        },
        // 移动主题到指定收藏夹
        async topicMove(fromFolder: number, toFolder: number, tid: number, pid?: number | undefined) {
            const favorId = pid ? `${tid}_${pid}` : `${tid}`
            // 添加到新收藏夹
            await api().topicAdd(toFolder, tid, pid)
            // 从旧收藏夹中删除
            return await api().topicDelete(fromFolder, [favorId])
        },
    },
})